<template>
  <div class="scatter-chart">
    <div ref="scatterChart" id="container"></div>
    <div class="loading" v-if="isLoading" v-loading="isLoading"></div>
  </div>
</template>
<script setup>
import { Scatter, G2 } from '@antv/g2plot'
import { onMounted, watch, ref } from 'vue'
import { useKnowledgeStore } from '@/stores/knowledge-store'

const props = defineProps({
  knowledgeInfo: Object,
  doubleDimensionData: Array,
  studentSituationValue: String,
  isLoading: Boolean
})

const knowledgeStore = useKnowledgeStore()

const scatterPlot = ref(null)

const getChartOptions = () => {
  console.log(props.doubleDimensionData)

  let sum = 0
  props.doubleDimensionData?.forEach(item => {
    sum += item?.count || 0
  })
  const averageCount = sum / (props.doubleDimensionData?.length || 1)
  const options = {
    renderer: 'canvas',
    useDeferredLabel: 500,
    appendPadding: 5,
    autoFit: true,
    xAxis: {
      nice: true,
      label: {
        autoRotate: false,
        autoHide: {
          type: 'equidistance',
          cfg: {
            minGap: 6
          }
        }
      },
      title: {
        text: '得分率'
      },
      max: 1,
      formatter: v => `${(v * 100).toFixed(2)}`,
      range: [0.05, 0.95],
      limitInPlot: false
    },
    yAxis: {
      nice: true,
      label: {
        autoHide: true,
        autoRotate: false
      },
      title: {
        text: '习题量'
      },
      max:
        Math.max(
          ...(props.doubleDimensionData?.map(item => item.count) || [])
        ) * 1.2 || 1,
      range: [0.1, 1]
    },
    animation: true,
    size: 4,
    tooltip: {
      showTitle: false,
      showMarkers: false,
      showCrosshairs: true,
      crosshairs: {
        type: 'xy'
      },
      fields: ['student_name', 'rate', 'count']
    },
    data: props.doubleDimensionData || [],
    xField: 'rate',
    yField: 'count',
    shape: 'circle',
    // 颜色使用的字段是quadrant，计算颜色操作是在StudentStatus.vue中完成的
    colorField: 'quadrant',
    color: ({ quadrant }) => {
      return quadrant
    },

    meta: {
      rate: {
        alias: '得分率',
        max: 1,
        formatter: v => `${(v * 100).toFixed(2)}%`
      },
      count: {
        alias: '习题量'
      },
      student_name: {
        alias: '姓名'
      }
    },
    legend: false,

    brush: {
      enabled: true,
      action: 'filter',
      mask: {
        style: {
          fill: 'rgba(0, 0, 0, .2)'
        }
      },
      button: {
        text: '重置'
      }
    }
  }
  options.annotations = [
    {
      type: 'line',
      start: ['start', averageCount],
      end: ['end', averageCount],
      style: {
        stroke: '#1890FF',
        fill: '#1890FF',
        lineWidth: 1
      }
    },
    {
      type: 'line',
      start: [props.knowledgeInfo?.rate / 100, 'start'],
      end: [props.knowledgeInfo?.rate / 100, 'end'],
      style: {
        stroke: '#1890FF',
        fill: '#1890FF',
        lineWidth: 1
      }
    }
  ]

  return options
}

const updateChart = () => {
  if (!scatterPlot.value) return
  const options = getChartOptions()
  scatterPlot.value.update(options)
}

onMounted(() => {
  const options = getChartOptions()
  scatterPlot.value = new Scatter('container', options)
  // 选中学生
  scatterPlot.value.on(G2.BRUSH_FILTER_EVENTS.AFTER_FILTER, () => {
    const filteredData = scatterPlot.value.chart.getData()
    const { setSelectedStudent } = knowledgeStore
    setSelectedStudent(filteredData)
  })
  // 重置时清空选中的学生
  scatterPlot.value.on(G2.BRUSH_FILTER_EVENTS.AFTER_RESET, () => {
    const { setSelectedStudent } = knowledgeStore
    setSelectedStudent([])
  })
  scatterPlot.value.render()
})

watch(
  () => knowledgeStore.selectedStudent,
  newValue => {
    if (newValue.length === 0 && scatterPlot.value) {
      // 重置刷选
      scatterPlot.value.chart.getComponents().forEach(co => {
        if (co.type === 'brush') {
          co.component.clear()
        }
      })
      // 更新图表
      scatterPlot.value.render()
    }
  }
)

watch(
  () => props.doubleDimensionData,
  () => {
    updateChart()
  }
)
</script>
<style lang="less" scoped>
.scatter-chart {
  position: relative;
  width: 100%;
  height: 150px;
  .loading {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

    :deep(.el-loading-spinner) {
      transform: translateY(-50%);
    }
  }
  #container {
    width: 100%;
    height: 100%;
  }
}
</style>
